package com.cskaoyan.rocketmq.delay;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.Charset;
import java.util.List;

/**
 * 创建日期: 2023/01/12 16:14
 *
 * @author ciggar
 */
public class DelayConsumer {

    // 延迟消息的消费者

    public static void main(String[] args) throws MQClientException {

        // 1. 构建消息消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("delay_consumer_group");

        // 2. 去注册中心注册
        consumer.setNamesrvAddr("localhost:9876");

        // 3. 设置消息监听器
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                long reciveTime = System.currentTimeMillis();
                System.out.println("收到消息时间：" + reciveTime);

                // 获取消息对象
                MessageExt messageExt = msgs.get(0);

                // 获取消息中的内容
                byte[] body = messageExt.getBody();

                String messageContent = new String(body, Charset.forName("utf-8"));

                System.out.println("messageContent:" + messageContent);

                // 返回消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 4. 订阅主题
        // * 表示一种过滤规则，这里表示订阅这个主题下的所有的消息
        consumer.subscribe("delay_topic","*");

        // 5. 启动
        consumer.start();

    }

}
